import Vue from 'vue'
import moment from "moment";

Vue.filter('numberWithCommas', function (value) {
  value = value.toString()
  return value.replace(/\B(?=(\d{3})+(?!\d))/g, ',')
})

Vue.filter('isNull', function (value, value2) {
  if (!value || value == 'null' || typeof value == undefined || typeof value == null) {
    if (value2){
      return value2 + '未录入'
    }else{
      return '未录入'
    }
  } else {
    return value
  }
})

Vue.filter('formatDate', function (value, type) {
  let formatData = "YYYY年MM月DD日"
  if (type == "datetime") {
    formatData = "YYYY年MM月DD日 HH:mm:ss"
  }
  if (value) {
    return moment(value).format(formatData)
  }
})

Vue.filter('formatBoolean', function (value) {
  if (value === "true") {
    return "是"
  } else {
    return "否"
  }
})

Vue.filter('formatNumber', function (num) {
  var result = '', counter = 0;
  num = (num || 0).toString();
  for (var i = num.length - 1; i >= 0; i--) {
    counter++;
    result = num.charAt(i) + result;
    if (!(counter % 3) && i != 0) { result = ',' + result; }
  }
  return result;
})

Vue.filter('proportion', function (value, count, fixed = 2) {
  return (value / count * 100).toFixed(fixed)
})

Vue.filter('age', function (value) {
  let returnAge
  let strBirthdayArr = new Date(value).toLocaleDateString().split("/")
  let birthYear = strBirthdayArr[0]
  let birthMonth = strBirthdayArr[1]
  let birthDay = strBirthdayArr[2]

  let d = new Date()
  let nowYear = d.getFullYear()
  let nowMonth = d.getMonth() + 1
  let nowDay = d.getDate()

  if (nowYear == birthYear) {
    returnAge = 0;//同年 则为0岁
  }
  else {
    let ageDiff = nowYear - birthYear; //年之差
    if (ageDiff > 0) {
      if (nowMonth == birthMonth) {
        let dayDiff = nowDay - birthDay;//日之差
        if (dayDiff < 0) {
          returnAge = ageDiff - 1;
        }
        else {
          returnAge = ageDiff;
        }
      }
      else {
        let monthDiff = nowMonth - birthMonth;//月之差
        if (monthDiff < 0) {
          returnAge = ageDiff - 1;
        }
        else {
          returnAge = ageDiff;
        }
      }
    }
    else {
      returnAge = -1;//返回-1 表示出生日期输入错误 晚于今天
    }
  }

  return returnAge;//返回周岁年龄
})